import axios from 'axios'
import router from '../router'
import { ElMessage } from 'element-plus'

// 创建axios实例对象
const request = axios.create({
  // baseURL:'https://m1.apifoxmock.com/m1/6616656-0-default',
  // baseURL:'http://localhost:8080'
  baseURL: '/api',
  timeout: 600000,
})

// axios的响应 response 拦截器
request.interceptors.response.use(
  (response) => {
    return response.data
  },
  (error) => {
    if (error.response && error.response.status === 401) {
      localStorage.removeItem('userInfo')
      ElMessage.error('登录状态已过期，请重新登录')
      router.replace('/login')
    }
    return Promise.reject(error)
  },
)

// axios的请求 request 拦截器
request.interceptors.request.use(
  (config) => {
    //成功回调
    const userInfoStr = localStorage.getItem('userInfo')
    if (userInfoStr) {
      try {
        const userInfo = JSON.parse(userInfoStr)
        if (userInfo && userInfo.token) {
          config.headers.Authorization = userInfo.token
        }
      } catch (error) {
        console.warn('解析用户信息失败:', error)
      }
    }
    return config
  },
  (error) => {
    //失败回调
    return Promise.reject(error)
  },
)

export default request
